package org.fireflow2.designer.eclipse.wizards;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.IWizardContainer;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWizard;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.fireflow.model.InvalidModelException;
import org.fireflow.model.io.SerializerException;
import org.fireflow.pdl.fpdl20.io.FPDLSerializer;
import org.fireflow.pdl.fpdl20.misc.FpdlConstants;
import org.fireflow.pdl.fpdl20.process.WorkflowProcess;
import org.fireflow.pdl.fpdl20.process.impl.WorkflowProcessImpl;

/**
 * This is a sample new wizard. Its role is to create a new file resource in the
 * provided container. If the container resource (a folder or a project) is
 * selected in the workspace when the wizard is opened, it will accept it as the
 * target container. The wizard creates one file with the extension "xml". If a
 * sample multi-page editor (also available as a template) is registered for the
 * same extension, it will be able to open it.
 */

public class NewWorkflowProcessWizard extends Wizard implements INewWizard {

	private NewWorkflowProcessWizardPage page;
	private ISelection selection;

	/**
	 * Constructor for NewWorkflowProcessWizard.
	 */
	public NewWorkflowProcessWizard() {
		super();
	}

	/**
	 * Adding the page to the wizard.
	 */

	public void addPages() {
		IStructuredSelection tmpSelection = new StructuredSelection();
		if (selection!=null && (selection instanceof IStructuredSelection)){
			tmpSelection = (IStructuredSelection)selection;
		}
		
		
		page = new NewWorkflowProcessWizardPage("NewProcessWizardPage",tmpSelection);
		page.setDescription("Create a new fire workflow process v2.");
		page.setFileName("newProcessDefinition"+"."+FpdlConstants.PROCESS_FILE_SUFFIX);
		page.setFileExtension(FpdlConstants.PROCESS_FILE_SUFFIX);//
		
		addPage(page);
	}

	/**
	 * This method is called when 'Finish' editReturnBindingExpressionButton is pressed in the wizard. We
	 * will create an operation and run it using wizard as execution context.
	 */
	public boolean performFinish() {
		final IFile file = page.createNewFile();

		IRunnableWithProgress op = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor)
					throws InvocationTargetException {
				try {
					doFinish(file, monitor);
				} catch (IOException e) {
					throw new InvocationTargetException(e);
				} catch (SerializerException e) {
					throw new InvocationTargetException(e);
				} catch (CoreException e) {
					throw new InvocationTargetException(e);
				} catch (InvalidModelException e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
		};
		try {
			IWizardContainer container = this.getContainer();
			container.run(true, false, op);
		} catch (InterruptedException e) {

			return false;
		} catch (InvocationTargetException e) {
			//TODO 如何显示错误信息？
//			Throwable realException = e.getTargetException();
//			MessageDialog.openError(getShell(), "Error", realException
//					.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * The worker method. It will find the container, create the file if missing
	 * or just replace its contents, and open the editor on the newly created
	 * file.
	 */
	private void doFinish(final IFile file, IProgressMonitor monitor)
			throws IOException, SerializerException, CoreException,
			InvalidModelException {
		monitor.beginTask("Create workflow process...", 100);
		String fileName = file.getName();

		InputStream stream = openContentStream(fileName);
		monitor.worked(20);
		if (file.exists()) {
			file.setContents(stream, true, true, monitor);
		} else {
			file.create(stream, true, monitor);
		}
		stream.close();
		monitor.worked(50);

		monitor.setTaskName("Opening file for editing...");
		// TODO
		getShell().getDisplay().asyncExec(new Runnable() {
			public void run() {
				IWorkbenchPage page = PlatformUI.getWorkbench()
						.getActiveWorkbenchWindow().getActivePage();
				try {
					IDE.openEditor(
							page,
							file,
							"org.fireflow2.designer.eclipse.editors.FireflowMultiPageEditor",
							true);
				} catch (PartInitException e) {
				}
			}
		});
		monitor.done();
	}

	/**
	 * We will initialize file contents with a sample text.
	 */

	private InputStream openContentStream(String fileName) 
		throws IOException,SerializerException,InvalidModelException{
		String tmp = fileName.toUpperCase();
		int idx = tmp.indexOf(FpdlConstants.PROCESS_FILE_SUFFIX.toUpperCase());
		String workflowProcessName = null;
		if (idx>0){
			workflowProcessName = fileName.substring(0,idx-1);
		}else{
			workflowProcessName = fileName;
		}
		WorkflowProcess process = new WorkflowProcessImpl(workflowProcessName,workflowProcessName);
		
		/*
		Subflow mainFlow = process.getMainflow();
		Diagram mainFlowDiagram = process.getDiagramBySubflowId(mainFlow.getId());
		if (mainFlowDiagram==null){
			String diagramId = UUID.randomUUID().toString();
			mainFlowDiagram = new DiagramImpl(diagramId,mainFlow.getId());
			
			String poolShapeId = UUID.randomUUID().toString();
			PoolShape poolShape = new PoolShapeImpl(poolShapeId);
			poolShape.setWorkflowElementRef(mainFlow.getId());

			mainFlowDiagram.addPool(poolShape);
			process.addDiagram(mainFlowDiagram);
		}
		*/
		
		ByteArrayInputStream inStream = null;
		FPDLSerializer ser = new FPDLSerializer();
		String contents = null;

		contents = ser.serializeToXmlString(process);
		inStream = new ByteArrayInputStream(contents.getBytes("UTF-8"));

		return inStream;
	}

	/**
	 * We will accept the selection in the workbench to see if we can initialize
	 * from it.
	 * 
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
		setNeedsProgressMonitor(true);
		setWindowTitle("Create a new Fire Workflow Process File v2");
	}
}
